import { View, Text, Image } from "@tarojs/components";
import { useEffect, useState } from "react";
import clsx from "clsx";
import "./index.scss";

export interface MenuItem {
  name: string; // 菜单名称
  id: string; // 菜单下标
}

const QNavBar = (props) => {
  const { menu = [], index = 0, onClick, className, padding = 120 } = props;
  const [activeIndex, setActiveIndex] = useState(index);

  useEffect(() => {
    setActiveIndex(index);
  }, [index]);

  function renderMenu() {
    return menu?.map((item, idx) => {
      const menuItem = item as MenuItem;
      const isSelect = activeIndex === idx;
      return (
        <View
          key={item.icon}
          onClick={() => {
            setActiveIndex(idx);
            if (onClick) {
              onClick(idx);
            }
          }}
          className={clsx(
            "q-single-bar flex-1 border-box flex-center",
            isSelect ? "active" : ""
          )}
        >
          {item.icon ? (
            <Image
              src={isSelect ? item.iconSel : item.icon}
              className="q-single-bar-image mr-8"
            />
          ) : null}
          <Text className={clsx("text", isSelect ? "cl-theme" : "cl-title")}>
            {menuItem.name}
          </Text>
        </View>
      );
    });
  }

  return menu.length ? (
    <View
      className={clsx("q-nav-bar border-box dis-flex align-center", className)}
      style={{ padding: `0 ${padding}rpx` }}
    >
      {renderMenu()}
    </View>
  ) : null;
};

export default QNavBar;
